package se.webbzon.oschi01.world;

import java.awt.geom.Point2D;
import java.io.IOException;

import se.webbzon.oschi01.utils.ObjectUtils;

public class Regions {
		
	public static ObservableRegion observableRegion(final Region r) {
		return new ObservableRegion() {

			@Override public boolean addChunk(Chunk chunk) {
				if (r.addChunk(chunk)) {
					setChanged();
					notifyObservers(new RegionEvent(this,Action.CHUNK_ADDED,chunk));
					return true;
				} else
					return false;
			}

			@Override public boolean removeChunk(Chunk chunk) {
				if (r.removeChunk(chunk)) {
					setChanged();
					notifyObservers(new RegionEvent(this,Action.CHUNK_REMOVED,chunk));
					return true;
				} else
					return false;
			}

			@Override public boolean hasChunk(Chunk chunk) {
				return r.hasChunk(chunk);
			}

			@Override public int chunks() {
				return r.chunks();
			}

			@Override public Chunk getChunk(int i) {
				return r.getChunk(i);
			}

			@Override public Chunk getChunk(Point2D coordinates) {
				return r.getChunk(coordinates);
			}

			@Override public Point2D getCoordinate() {
				return r.getCoordinate();
			}

			@Override public void setCoordinate(int x, int z) {
				r.setCoordinate(x, z);
				setChanged();
				notifyObservers(new RegionEvent(this,Action.MOVED,r.getCoordinate()));
			}

			@Override public boolean writeback() throws IOException {
				if (r.writeback()) {
					setChanged();
					notifyObservers(new RegionEvent(this,Action.SAVED,null));
					return true;
				} else
					return false;
			}

			@Override public void free() {
				r.free();
				setChanged();
				notifyObservers(new RegionEvent(this,Action.FREED,null));
			}
			
		};
	}
	
	public static Region unmodifiableRegion(final Region r) {
		return new Region() {
			
			@Override public Point2D getCoordinate() {
				return r.getCoordinate();
			}

			@Override public boolean addChunk(Chunk chunk) {
				throw new UnsupportedOperationException();
			}

			@Override public boolean removeChunk(Chunk chunk) {
				throw new UnsupportedOperationException();
			}

			@Override public Chunk getChunk(Point2D coordinates) {
				return r.getChunk(coordinates);
			}

			@Override public int chunks() {
				return r.chunks();
			}

			@Override public Chunk getChunk(int i) {
				return r.getChunk(i);
			}

			@Override public boolean hasChunk(Chunk chunk) {
				return r.hasChunk(chunk);
			}
			
			@Override public boolean equals(Object o) {
				return ObjectUtils.equals(Region.class, r, o);
			}

			@Override public void setCoordinate(int x, int z) {
				throw new UnsupportedOperationException();
			}

			@Override public boolean writeback() throws IOException {
				return false;
			}

			@Override public void free() {
				r.free();
			}
			
		};
	}

}
